import express from 'express'
import db from '../config/db.js'

const router = express.Router()

const safeParse = (txt) => {
  try { return JSON.parse(txt || '[]') } catch { return [] }
}

// 获取我的训练列表
router.get('/', async (_req, res) => {
  try {
    const conn = await db.getConnection()
    conn.query('SELECT id, name, level, equipments, parts, warmup, stretch, createdAt FROM setup_trainings ORDER BY id DESC', (err, results) => {
      conn.release()
      if (err) return res.status(500).json({ message: '数据库查询失败', error: String(err) })
      const list = (results || []).map((r) => ({
        id: r.id,
        name: r.name,
        level: r.level,
        equipments: safeParse(r.equipments),
        parts: safeParse(r.parts),
        warmup: r.warmup === 1 || r.warmup === true,
        stretch: r.stretch === 1 || r.stretch === true,
        createdAt: Number(r.createdAt) || Date.now(),
      }))
      res.json(list)
    })
  } catch (e) {
    res.status(500).json({ message: '数据库连接失败', error: String(e) })
  }
})

// 获取单条
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params
    const conn = await db.getConnection()
    conn.query('SELECT id, name, level, equipments, parts, warmup, stretch, createdAt FROM setup_trainings WHERE id = ? LIMIT 1', [id], (err, results) => {
      conn.release()
      if (err) return res.status(500).json({ message: '数据库查询失败', error: String(err) })
      if (!results || results.length === 0) return res.status(404).json({ message: '未找到记录' })
      const r = results[0]
      res.json({
        id: r.id,
        name: r.name,
        level: r.level,
        equipments: safeParse(r.equipments),
        parts: safeParse(r.parts),
        warmup: r.warmup === 1 || r.warmup === true,
        stretch: r.stretch === 1 || r.stretch === true,
        createdAt: Number(r.createdAt) || Date.now(),
      })
    })
  } catch (e) {
    res.status(500).json({ message: '数据库连接失败', error: String(e) })
  }
})

// 新建我的训练计划
router.post('/', async (req, res) => {
  try {
    const { name, level, equipments = [], parts = [], warmup = false, stretch = false, createdAt } = req.body || {}
    if (!name || !level) {
      return res.status(400).json({ message: '缺少必要字段: name 或 level' })
    }

    const sql = `INSERT INTO setup_trainings (name, level, equipments, parts, warmup, stretch, createdAt)
                 VALUES (?, ?, ?, ?, ?, ?, ?)`
    const params = [
      String(name),
      String(level),
      JSON.stringify(equipments || []),
      JSON.stringify(parts || []),
      warmup ? 1 : 0,
      stretch ? 1 : 0,
      createdAt || Date.now(),
    ]

    const conn = await db.getConnection()
    conn.query(sql, params, (err, result) => {
      conn.release()
      if (err) {
        return res.status(500).json({ message: '数据库写入失败', error: String(err) })
      }
      res.json({ id: result.insertId, ...req.body })
    })
  } catch (e) {
    res.status(500).json({ message: '服务器错误', error: String(e) })
  }
})

// 删除
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params
    const conn = await db.getConnection()
    conn.query('DELETE FROM setup_trainings WHERE id = ?', [id], (err, result) => {
      conn.release()
      if (err) return res.status(500).json({ message: '数据库删除失败', error: String(err) })
      res.json({ affectedRows: result.affectedRows })
    })
  } catch (e) {
    res.status(500).json({ message: '数据库连接失败', error: String(e) })
  }
})

export default router

